package com.dswz.controller.pc;

import com.dswz.po.UserOrder;
import com.dswz.service.UserOrderService;
import com.dswz.utils.EncryptUtil;
import com.dswz.utils.Utils;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({ "/" })
public class PayController {
	private Logger logger = LogManager.getLogger(PayController.class);
	@Autowired
	private UserOrderService userOrderService;

	@RequestMapping({ "/cxding/notify" })
	@ResponseBody
	public Object notify(HttpServletRequest request) {
		long startTime = System.currentTimeMillis();
		UserOrder userOrder = null;
		String result = "";
		try {
			String orderid = request.getParameter("orderid");

			String opstate = request.getParameter("opstate");

			String ovalue = request.getParameter("ovalue");

			String sign = request.getParameter("sign");
			this.logger.info("orderid:" + orderid + "opstate:" + opstate + "ovalue:" + ovalue + "sign:" + sign + "页面来源:"
					+ request.getHeader("referer") + "客户端:" + request.getHeader("user-agent") + " 客户端ip: "
					+ Utils.getUserRealAddress(request));
			userOrder = this.userOrderService.getUserOrderById(orderid);
			String key = "C094DAD5AB2DC7E5BAA41C8470A0D515";
			String str = "orderid=%s&opstate=%s&ovalue=%s&key=%s";
			String strTemp = String.format(str, new Object[] { orderid, opstate, ovalue, key });
			String b_sign = EncryptUtil.encodeByMD5(strTemp);
			this.logger.info("b_sign:" + b_sign);
			if (b_sign.equals(sign)) {
				this.logger.info("支付成功!");
				result = "success";
				userOrder.setUserOrderState(Byte.valueOf((byte) 1));
				userOrder.setUserOrderFinishTime(new Date());
				this.userOrderService.updateUserOrder(userOrder);
			} else {
				this.logger.error("验签失败!");
				result = "fail";
				userOrder.setUserOrderState(Byte.valueOf((byte) 3));
				userOrder.setUserOrderFinishTime(new Date());
				userOrder.setUserOrderFailMessage("验签失败!");
				this.userOrderService.updateUserOrder(userOrder);
			}
			long endTime = System.currentTimeMillis();
			this.logger.info("程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result = "fail";
		}
		return result;
	}
}
